package com.daiqee.shiro.filter;

import javax.servlet.ServletRequest;

import javax.servlet.ServletResponse;

import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;
import org.springframework.beans.factory.annotation.Autowired;

import com.daiqee.pojo.Department;
import com.daiqee.pojo.Role;
import com.daiqee.pojo.User;
import com.daiqee.service.impl.DepartmentService;
import com.daiqee.service.impl.RoleService;

/**
 * <p>perms 实现or关系 , *号任意权限</p>
 * <p>XX部:* -> XX部:XX or XX部:AA ...</p> 
 * 将*号替换成任意权限
 * 
 * @since JDK 1.8
 * @version  V2.1
 * @author RichardTang 
 * @date: 2018年5月31日
 * @package com.daiqee.shiro.filter
 * @copyright:Copyright (c) 2018, 1245811923@qq.com All Rights Reserved.
 */
public class PermsOrOfAuthorizationFilter extends AuthorizationFilter{

	@Autowired
	private RoleService roleService;
	
	@Autowired
	private DepartmentService departmentService;
	
	@Override
	protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue)
			throws Exception {
		
		//令牌对象
		Subject subject = getSubject(request, response);  
		//当前账号
		User currentUser = (User) subject.getPrincipal();
		//权限值
		String[] permsArray = (String[]) mappedValue;  
        
		//查询角色 和 部门
		Role currentRole = roleService.selectById(currentUser.getUserRole());
		Department currentDepartment = departmentService.selectById(currentUser.getUserDepartment());
		
		//拼接成权限字符串
		String userPerms = currentDepartment.getDeptName() + ":" + currentRole.getRoleName();
		
		for(int i = 0;i < permsArray.length;i++) {
			
			//拿到第i个资源权限
			String resourcePerms = permsArray[i];

			//判断该资源是否包含*号,并拿到索引;
			int starIndex = resourcePerms.indexOf("*");
			
			//如果资源权限等于 *:* 就代表 任意部门 任意角色,所有都可以访问
			if(resourcePerms.equals("*:*")) {
				
				return true;
			}else if(resourcePerms.contains("*")) {//如果不等于*:*同时又包含有*号的情况
				
				//吧资源权限和用户权限切割成 部门 角色 两部分
				String[] userPermsSplit = userPerms.split(":");
				String[] pathPermsSplit = resourcePerms.split(":");
				
				//大于0,代表*号在结尾(在角色位置)
				if(starIndex > 0) {
					
					//*号在结尾,匹配部门即可,部门:任意角色
					if(pathPermsSplit[0].equals(userPermsSplit[0])) {
						
						//匹配上了直接返回,没匹配上,循环下一次
						return true;
					}
				}else {//*号在部门位置
					
					//*号在部门位置匹配角色即可
					if(pathPermsSplit[1].equals(userPermsSplit[1])) {
						return true;
					}
				}
			}else {//不带*号的情况
				if(subject.isPermitted(resourcePerms)) {
					return true;
				};
			}
		}
		
		//资源权限循环结束,都没有匹配上,代表没有访问该资源的权限
		return false;
	}
}
